package com.ruoyi.workflow.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.domain.CarPackageAuditVo;
import com.ruoyi.workflow.domain.HistoricActivityVo;
import com.ruoyi.workflow.service.IBpmnNodeService;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.ITaskDoneService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TaskDoneServiceImpl implements ITaskDoneService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnNodeService bpmnNodeService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private HistoryService historyService;
    @Override
    public TableDataInfo selectCarPackageAuditList(CarPackageAudit carPackageAudit) {
        TableDataInfo info = new TableDataInfo();
        info.setCode(HttpStatus.SUCCESS);
        info.setMsg("查询成功");

       //2. 以当前用户作为负责人, 统计任务个数
        String username = SecurityUtils.getUsername();
        long count = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .finished()
                .count();
        //3. 如果数量为 0, 返回空数据
        if (count==0){
            info.setTotal(count);
            info.setRows(Collections.emptyList());
            return info;
        }
        //1. 接收前端的分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
       //4. 如果有数据, 构建分页条件
        int startIndex = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
       //5. 以当前用户作为负责人, 查询所有已经完成的任务列表
        List<HistoricTaskInstance> listHistory = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .orderByTaskCreateTime()
                .desc()
                .finished()
                .listPage(startIndex, pageDomain.getPageSize());
        //6. 创建一个集合, 用于存储最终返回的数据列表
        ArrayList<CarPackageAudit> list = new ArrayList<>(listHistory.size());
        //7. 遍历任务列表
        for (HistoricTaskInstance historyTask : listHistory) {
            //8. 基于任务对象, 得到流程实例 id, 查询流程实例对象
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(historyTask.getProcessInstanceId())
                    .singleResult();
            //9. 基于流程实例对象, 得到业务标识, 基于业务标识查询审核记录对象
            String businessKey = instance.getBusinessKey();
            CarPackageAudit audit = carPackageAuditService.getById(businessKey);
            CarPackageAuditVo vo = new CarPackageAuditVo();
            //10. 将审核记录对象的数据拷贝到 vo 中, 并补充相应字段(完成时间/任务名称/负责人)
            BeanUtils.copyBeanProp(vo,audit);
            //11. 查询任务的创建人并设置到审核记录
            SysUser user = sysUserService.selectUserById(Long.parseLong(audit.getCreatorId()));
            vo.setCreatorName(user.getNickName());
            //设置结束时间
            vo.setFinishedTime(historyTask.getEndTime());
            //设置任务名称
            vo.setTaskName(historyTask.getName());
            //设置任务id
            vo.setTaskId(historyTask.getId());
            //设置负责人--》我的已办，所以审核人为当前用户
            vo.setAuditors(SecurityUtils.getLoginUser().getUser().getNickName());
            //12. 将 vo 对象加入返回的集合中
            list.add(vo);
        }
       //13. 返回分页数据
        info.setRows(list);
        return info;
    }

    @Override
    public List<HistoricActivityVo> selectHistoryList(String instanceId) {
        List<HistoricActivityVo> list = new ArrayList<>();
        //1. 基于流程实例id查询到历史任务(已完成)列表
        List<HistoricActivityInstance> userTask = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId)//流程实例id
                .activityType("userTask")//基于活动类型为“userTask”
                .orderByHistoricActivityInstanceStartTime()//基于开始时间
                .asc()
                .finished()
                .list();
        //2. 遍历历史任务集合, 基于任务id查询批注信息
        for (HistoricActivityInstance instance : userTask) {
            HistoricActivityVo historicActivityVo = new HistoricActivityVo();
            BeanUtils.copyBeanProp(historicActivityVo,instance);
//根据任务id和批注的类型来查批注信息
            List<Comment> taskComments = taskService.getTaskComments(instance.getTaskId(),"comment");
            historicActivityVo.setComment(taskComments.get(0).getFullMessage());
            SysUser sysUser = sysUserService.selectUserByUserName(instance.getAssignee());
            if (sysUser!=null){
                historicActivityVo.setAssigneeName(sysUser.getNickName());
            }
            list.add(historicActivityVo);
        }
        //3. 将批注信息保存到对象, 最终返回数据
        return list;
    }

}
